package com.xj.controller;

import com.xj.entity.Xj;
import com.xj.service.XjService;
import com.xj.util.JedisUtil;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @program: demo2
 * @packageName: com.xj.controller
 * @className XjControler
 * @description: TODO
 * @author: xj
 * @create: 2021-01-08 12:31:11
 **/
@RestController
public class XjControler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private XjService xjService;
    @Autowired
    private JedisUtil jedisUtil;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping(value = "hello", method = RequestMethod.GET)
    @ResponseBody
    public List<Xj> hello() {
        logger.info("打印日志：hello接口调用");

        String setResult = jedisUtil.set("hello", "world2");
        System.out.println(setResult);
        String getResult = jedisUtil.get("hello");
        System.out.println(getResult);
        return xjService.getall();
    }

    @RequestMapping(value = "lock", method = RequestMethod.GET)
    @ResponseBody
    public boolean lock() {
        boolean lock = jedisUtil.tryExpireLock();
        System.out.println("获取锁：" + lock);
        return lock;
    }

    @RequestMapping(value = "hello2", method = RequestMethod.GET)
    @ResponseBody
    public String hello2() {
        RBucket<String> key = redissonClient.getBucket("newday");
        key.set("新的数据");
        key.set("新的数2"); //会覆盖之前的值，get的结果为新的数2
        System.out.println("获取到新存入的数据：" + key.get());
        // 获取字符串格式的数据
        RBucket<String> keyObj = redissonClient.getBucket("newday");
        if (keyObj == null) {
            System.out.println("获取到昨天存入的数据：null");
        } else {
            String s = keyObj.get();
            System.out.println("获取到昨天存入的数据：" + s);
        }
        return "redis";
    }

    @RequestMapping(value = "lock2", method = RequestMethod.GET)
    @ResponseBody
    public boolean lock2() {
        RLock lock = redissonClient.getLock("RedissonLock");
        try {
            //等待100秒后，再等10秒解锁
            boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (res) {
                System.out.println("执行redisson的锁操作成功");
            }else{
                System.out.println("执行redisson的锁操作失败");
                return false;
            }
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally{
            lock.unlock();
            System.out.println("redisson的解锁成功");
        }
        return true;
    }


    @RequestMapping(value = "send", method = RequestMethod.GET)
    @ResponseBody
    public String send() {
        rocketMQTemplate.send("xiongjie-topic",
                MessageBuilder.withPayload("hello,this is my spring boot rocketmq msg").build()
        );

        System.out.println("发送消息OK");
        return "发送消息OK";
    }

    @RequestMapping(value = "txSend", method = RequestMethod.GET)
    @ResponseBody
    public String txSend() {
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("xiongjie-tx-topic2",
                MessageBuilder.withPayload("this is a tx msg").build(),
                "this is local tx need arg"
        );

        if(sendResult.getSendStatus().equals(SendStatus.SEND_OK) && sendResult.getLocalTransactionState().equals(LocalTransactionState.COMMIT_MESSAGE)){
            System.out.println("事务发送成功，并且本地事务执行成功");
        }else{
            System.out.println("事务发送失败，或者本地事务执行失败");
        }

        String sendStatus = sendResult.getSendStatus().name();
        String localTXState = sendResult.getLocalTransactionState().name();
        System.out.println("send status="+sendStatus+",localTransactionState="+localTXState);

        System.out.println("发送事务消息OK");
        return "发送事务消息OK";
    }

}
